package cn.cloudtogo.server.atomapi;

import cn.cloudtogo.common.Assert;
import cn.cloudtogo.common.atomapi.token.ApiToken;
import cn.cloudtogo.common.atomapi.token.ApiTokenQuery;
import cn.cloudtogo.common.model.ApiTokenDao;
import cn.cloudtogo.common.model.ApiTokenModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @author yaolianhua789@gmail.com
 **/
@Service
@Slf4j
public class GendbApiTokenQuery implements ApiTokenQuery {

    private final ApiTokenDao apiTokenDao;
    private final ApiTokenObjectConverterHelper apiTokenObjectConverterHelper;

    public GendbApiTokenQuery(ApiTokenDao apiTokenDao,
                              ApiTokenObjectConverterHelper apiTokenObjectConverterHelper) {
        this.apiTokenDao = apiTokenDao;
        this.apiTokenObjectConverterHelper = apiTokenObjectConverterHelper;
    }

    @Override
    public ApiToken query(String uuid, String notes) {

        Assert.argument(StringUtils.hasText(uuid), () -> "uuid is required");
        Assert.argument(StringUtils.hasText(notes), () -> "token name is required");

        ApiTokenModel model = apiTokenDao.query(uuid, notes);

        Assert.notNull(model, () -> String.format("Can not found token '%s'", uuid), 404);
        ApiTokenCreateParam apiTokenCreateParam = apiTokenObjectConverterHelper.read(ApiTokenCreateParam.class, model.getJson());
        ApiToken apiToken = ApiToken.of(model.getNotes(), model.getToken(), model.getType(), apiTokenCreateParam.getExpiration());

        apiToken.setDisable(model.isDisable());
        return apiToken;
    }
}
